package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/***
 * 公共字段自动填充的切面类
 */
@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    //定义切入点
    @Pointcut("execution(* com.sky.mapper..*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void AutoFillPointCut(){}

    /**
     * 前置通知，负责公共字段填充
     * @param joinPoint
     */
    @Before("AutoFillPointCut()")
    public void AutoFill(JoinPoint joinPoint){
        log.info("开始进行公共字段填充");
        //获取方法的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill operationType = signature.getMethod().getAnnotation(AutoFill.class);
        //获取参数--约定第一个参数为实体对象
        Object[] args = joinPoint.getArgs();
        Object object = args[0];

        //获取参数的设定值：时间和id
        LocalDateTime now = LocalDateTime.now();
        Long id = BaseContext.getCurrentId();

        //利用反射进行公共字段的填充
        //如果是插入需要额外设置创建人和创建时间
        if (operationType.value() == OperationType.INSERT)
        {
            try {
                Method setCreateTime = object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                setCreateUser.invoke(object,id);
                setCreateTime.invoke(object,now);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //不论是更新还是插入都需要设置更新时间和更新人员
        try {
            Method updateTime = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method updateUser = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            updateTime.invoke(object,now);
            updateUser.invoke(object,id);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
